package sk.hackcraft.multibox.server.net;

import org.json.JSONObject;

import sk.hackcraft.multibox.server.User;
import sk.nixone.http.ServletExchange;

abstract public class UserServlet extends JSONServlet {
	public static class PairingFailedException extends JSONServlet.ResultException {
		private static final long serialVersionUID = 6455899325699043037L;

		public PairingFailedException() {
			super("Pairing with token and secret failed.");
		}
		
		public String getResultType() {
			return "PAIRING_FAILED";
		}
	}
	
	public UserServlet(Server server) {
		super(server);
	}
	
	@Override
	public JSONObject doRequest(Method method, ServletExchange exchange, JSONObject response) {
		long token = Long.valueOf(exchange.getQueryValue("token"));
		
		System.out.println("Token: "+token);
		
		User user = server.box.getUser(
			token
		);
		
		System.out.println("User: "+user);
		
		if(user == null) {
			throw new PairingFailedException();
		}
		
		return doUserRequest(user, method, exchange, response);
	}
	
	abstract public JSONObject doUserRequest(User space, Method method, ServletExchange exchange, JSONObject response);
}
